package com.kovell.cairngormlite
{
	import avmplus.getQualifiedClassName;
	
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.rpc.remoting.RemoteObject;
	import mx.states.AddItems;

	public class ServiceLocator
	{
		private static const CONFIG_FILE:String = "config/cairngormlite-config.xml";
		
		private var services:Dictionary;
		
		private static var instance:ServiceLocator;
		
		public function ServiceLocator()
		{
			if(instance != null){
				trace("Object is created.");
			}
			else{				
				init();				
			}
			
			instance = this;
		}
		
		public static function getInstance():ServiceLocator{
			if(instance == null){
				instance = new ServiceLocator();
			}
			
			return instance;
		}
		
		private function init():void{			
			var service:HTTPService = new HTTPService();
			service.url = CONFIG_FILE;
			service.addEventListener(ResultEvent.RESULT, resultHandler);
			service.addEventListener(FaultEvent.FAULT, faultHandler);
			service.resultFormat = "e4x";
			service.useProxy = false;
			service.send();
			
			services = new Dictionary();
		}
		
		private function resultHandler(event:ResultEvent):void	{		
			trace(event);
			var x:XMLList = new XMLList(event.result.services.service);
						
			for(var i:int = 0; i < x.length(); i++){
				
				var id:String = x[i].@id;
				var destination:String = x[i].@destination;
				var showBusyCursor:String = x[i].@showBusyCursor;
				var type:String = x[i].@type;
				
				if("remote" == type){	
					var rc:Class = getDefinitionByName("mx.rpc.remoting.RemoteObject") as Class;
					var ro:RemoteObject = (new rc() as RemoteObject);
					ro.destination = destination;
					ro.showBusyCursor = true;
					
					services[id] = ro;
				}
				else{
					trace("This is non remote object type. not support yet.");
				}
			}
		}
		
		private function faultHandler(event:FaultEvent):void{
			trace(event);
		}
		
		public function getRemoteObject(serviceId:String):RemoteObject{			
			return (this["services"] as Dictionary)[serviceId];
		}
		
	}
}